package com.taotao.common.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.apache.commons.lang3.StringUtils;

import net.coobird.thumbnailator.Thumbnails;

/**
 * Created by hdwang on 2018/12/13.
 */
public class PicUtil {
	
    private static Integer desFileSize=1000;
    private static Integer desMaxWidth=750;
    private static Integer desMaxHeight=1334;
 
    public static void main(String[] args) {
 
        PicUtil.commpressPicForScale("E://500089194.jpg","E://500089194.jpg"); // 图片小于1000kb


    }

    /**
     *  根据指定大小和指定精度压缩图片
     * @param srcPath 源图片地址
     * @param desPath 目标图片地址
     */
    public static String commpressPicForScale(String srcPath, String desPath) {
        if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(srcPath)) {
            return null;
        }
        if (!new File(srcPath).exists()) {
            return null;
        }
        try {
            File srcFile = new File(srcPath);
            long srcFileSize = srcFile.length();
            System.out.println("源图片：" + srcPath + "，大小：" + srcFileSize / 1024
                                        + "kb");
            //获取图片信息
            BufferedImage bim = ImageIO.read(srcFile);
            int srcWidth = bim.getWidth();
            int srcHeight = bim.getHeight();

            //先转换成jpg
            Thumbnails.Builder builder = Thumbnails.of(srcFile).outputFormat("jpg");

            // 指定大小（宽或高超出会才会被缩放）
            if(srcWidth > desMaxWidth || srcHeight > desMaxHeight) {
                builder.size(desMaxWidth, desMaxHeight);
            }else{
                //宽高均小，指定原大小
                builder.size(srcWidth,srcHeight);
            }

            // 写入到内存
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
            builder.toOutputStream(baos);

            // 递归压缩，直到目标文件大小小于desFileSize
            byte[] bytes = commpressPicCycle(baos.toByteArray(), desFileSize, 1);

            // 输出到文件
            File desFile = new File(desPath);
            FileOutputStream fos = new FileOutputStream(desFile);
            fos.write(bytes);
            fos.close();

            System.out.println("目标图片：" + desPath + "，大小" + desFile.length() / 1024 + "kb");
            System.out.println("图片压缩完成！");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return desPath;
    }
 
    private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
       // File srcFileJPG = new File(desPath);
        long srcFileSizeJPG = bytes.length;
        // 2、判断大小，如果小于500kb，不压缩；如果大于等于500kb，压缩
        if (srcFileSizeJPG <= desFileSize * 1024) {
            return bytes;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(
                                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(
                                new BigDecimal(accuracy)).intValue();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
    }
    
    
	public static byte[] toByteArray(String filePath) throws IOException {
		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException("file not exists");
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}


    /**
     * 检查图片是否含有二维码
     * @param path
     * @return
     */
    public static String checkQRCode(String path) {
        String content=null;
        BufferedImage image;
        try{
            image= ImageIO.read(new File(path));
            LuminanceSource source=new BufferedImageLuminanceSource(image);
            Binarizer binarizer=new HybridBinarizer(source);
            BinaryBitmap binaryBitmap=new BinaryBitmap(binarizer);
            Map<DecodeHintType,Object> hints=new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET,"UTF-8");
            System.out.println("checkQRCode path-->"+path);
            Result result=new MultiFormatReader().decode(binaryBitmap,hints);
            System.out.println("checkQRCode result-->"+result.getText());
            content=result.getText();
        }catch (IOException e) {
            e.printStackTrace();
        }catch (NotFoundException e){
            e.printStackTrace();
        }
        return content;
    }

}